<?php

class home extends CI_Controller {

    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     * 		http://example.com/index.php/welcome
     * 	- or -  
     * 		http://example.com/index.php/welcome/index
     * 	- or -
     * Since this controller is set as the default controller in 
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see http://codeigniter.com/user_guide/general/urls.html
     */
    protected $configs;

    function __construct() {
        parent::__construct();
        $this->load->model('backend/auth_model');
    }

    public function index() {
        require_once APPPATH . 'libraries/google-api-php-client0.6/src/Google_Client.php';
        require_once APPPATH . 'libraries/google-api-php-client0.6/src/contrib/Google_Oauth2Service.php';
        $client = new Google_Client();
        $client->setApplicationName("Google UserInfo PHP Starter Application");
        // Visit https://code.google.com/apis/console?api=plus to generate your
        // oauth2_client_id, oauth2_client_secret, and to register your oauth2_redirect_uri.
        $client->setClientId('619740911766-e483sg42gqish46g0uc3dbngv79igp42.apps.googleusercontent.com');
        $client->setClientSecret('QaChbqEJrGdcvKlq-BdSlzFi');
        $client->setRedirectUri(base_url('OAuth'));
        $client->setDeveloperKey('AIzaSyDJnQDtRXjtT9Eks4ArrlmxgWFVvogFX8w');
        $oauth2 = new Google_Oauth2Service($client);

        if (isset($_GET['code'])) {
            $client->authenticate($_GET['code']);
            $_SESSION['token'] = $client->getAccessToken();
            redirect(base_url("OAuth"));
            return;
        }

        if (isset($_SESSION['token'])) {
            $client->setAccessToken($_SESSION['token']);
        }

        if (isset($_REQUEST['logout'])) {
            unset($_SESSION['token']);
            unset($_SESSION['auth']['oauth']);
            $client->revokeToken();
        }
        $Data = null;
        if ($client->getAccessToken()) {
            $oauth_user = $oauth2->userinfo->get();

            // These fields are currently filtered through the PHP sanitize filters.
            // See http://www.php.net/manual/en/filter.filters.sanitize.php
            //$email = filter_var($oauth_user['email'], FILTER_SANITIZE_EMAIL);
            // The access token may have been updated lazily.
            $_SESSION['token'] = $client->getAccessToken();
            if (!isset($_SESSION['auth']['oauth'])) {
                $ause_secretkey = random_string('alnum', 32);
                $ause_username = $oauth_user["email"];
                $ause_password = random_string('alnum', 8);
                $paramsi = array(
                    "ause_key" => random_string('alnum', 8),
                    "ause_name" => $oauth_user["name"],
                    "ause_username" => $oauth_user["email"],
                    "ause_email" => $oauth_user["email"],
                    "ause_password" => md5("$ause_username$ause_password$ause_secretkey"),
                    "ause_authority" => "Guest",
                    "ause_picture" => isset($oauth_user["picture"]) ? $oauth_user["picture"] : base_url('libraries/images/user2.png'),
                    "ause_secretkey" => $ause_secretkey,
                    "ause_salt" => random_string('alnum', 8),
                    "ause_position" => 1,
                    'ause_insert' => date('Y-m-d H:i:s'),
                    'ause_lastlogin' => date('Y-m-d H:i:s')
                );
                $updates = array('ause_picture', 'ause_name', 'ause_lastlogin');
                $this->auth_model->insert_onduplicate_update_aupr($paramsi, $updates);
                $_SESSION['auth']['oauth'] = $oauth_user;
            }
            $state = (isset($_GET["state"]) and $_GET["state"] != "") ? $_GET["state"] : "service/auth/login";
            //if(isset($_SESSION["auth"]["user"])){
            redirect($state);
            //}
        } else {
            $Data["authUrl"] = $client->createAuthUrl();
            redirect($Data["authUrl"]);
        }
        die('form');
    }
    function logout() {
        session_destroy();
        redirect("OAuth");
    }

}
